collections.namedtuple(typename, field\_names[, verbose=False][, rename=False]) returns a new tuple subclass named typename. They are basically easy to create, lightweight object types. It can be referenced using object like variable deferencing or the standard tuple syntax.
Just like tuple they are also immutable.
For example, lets try to represent complex number in python:


In [ ]:
from collections import namedtuple
ComplexNumber = namedtuple('ComplexNumber', 'real imag', verbose=False)
c1 = ComplexNumber(1.0, 3.0)
print c1.real, c1.imag
#getattr can be used to get an attribute 
print getattr(c1, 'real')
#It would through an error
#c1.real = 5.0

However, named tuples are still backwards compatible with normal tuples, so the following will still work.


In [ ]:
print c1[0], c1[1]

You should use named tuples instead of tuples anywhere you think object notation will make your code more pythonic and more easily readable.
Moving further, we can also include our own function for immutable functions that have no functions. For example:


In [ ]:
import math
class ComplexNumber(namedtuple('ComplexNumber', 'real imag')):
    def modulus(self):
        return math.sqrt(self.real**2 + self.imag**2)

c1 = ComplexNumber(3.0, 4.0)
print c1.modulus()

Methods defined in namedtuple
__\_make__(iterable) is class method that makes a new instance from an existing sequence or iterable.


In [ ]:
some_list = [1, 4]
some_complex_number = ComplexNumber._make(some_list)
print some_complex_number.real, some_complex_number.imag

\_replace returns a new instance of the named tuple replacing specified fields with new values.


In [ ]:
foo_complex_number = ComplexNumber(1, 4)
foo_complex_number = foo_complex_number._replace(real=3)
print foo_complex_number.real

\_fields returns a tuple of strings listing the field names. Useful for introspection and for creating new named tuple types from existing named tuples. Subclassing is not useful for adding new, stored fields. Instead, simply create a new named tuple type from the _fields attribute


In [ ]:
print foo_complex_number._fields
WeirdComplexNumber = namedtuple('WeirdComplexNumber', ComplexNumber._fields+('weird',))
print WeirdComplexNumber._fields